<?php

namespace common\models;

use Yii;

/**
 * 缓存类数据模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class CacheModel extends \yii\base\Model {

    const CACHE_PREFIX_NAME = 'CACHE_';

    /**
     * 缓存前缀
     * @param type $append
     * @return type
     */
    protected static function getPrefixCacheName($append = null) {
        if ($append == null) {
            $append = static::className();
        }
        return static::CACHE_PREFIX_NAME . $append;
    }

    /**
     * 获取缓存信息
     * @param type $name
     * @param \common\models\callable $callable
     * ```php
     * function($name) { ... }
     * ```
     * ```or
     * [static::instance(), 'functionName']
     * ```
     * @return cachedata|\common\models\callable|null
     */
    public static function getCache($name = null, callable $callable = null) {
        $cacheName = static::getPrefixCacheName($name);
        $data = Yii::$app->cache->get($cacheName);
        if ($data !== false) {
            return $data;
        }
        if ($callable) {
            return call_user_func_array($callable, [$name]);
        }
        return $callable;
    }

    /**
     * 设置缓存
     * @param type $name
     * @param type $data
     * @param type $duration
     */
    public static function setCache($name, $data, $duration = 3600) {
        $cacheName = static::getPrefixCacheName($name);
        Yii::$app->cache->set($cacheName, $data, $duration);
    }

}
